package com.cskaoyan.controller.wx_cart;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.MemoryBean;
import com.cskaoyan.bean.bo.wx_cart.CollectAddOrDelBO;
import com.cskaoyan.bean.bo.wx_cart.CollectListBO;
import com.cskaoyan.bean.vo.wx_cart.CollectListVO;
import com.cskaoyan.service.wx_cart.WxCollectService;
import com.cskaoyan.util.common.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @program: market
 * @description: 微信前台收藏功能
 * @author: zhong
 * @create: 2022-07-21 14:54
 **/
@RestController
@RequestMapping("wx/collect")
public class WxCollectController {
    @Autowired
    WxCollectService wxCollectService;
    @Autowired
    MemoryBean memoryBean;

    private Integer getUserId(@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = memoryBean.tokenAndUserId.get(token);
        if (userId == null) {
            return -1;
        }
        return userId;
    }
    /**
     * @param pageReg:分页信息,"userId":memoryBean中获取
     * @return 收藏列表
     * @auther zhong
     * @description wx/collect/list 收藏列表
     */
    @GetMapping("list")
    public BaseRespVo list(CollectListBO pageReg, @RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.ok(null, "登录信息失效", Constant.NOT_FOUND_CODE);
        }
        CollectListVO collectListVO = wxCollectService.listCollectOp(pageReg, userId);
        return BaseRespVo.ok(collectListVO);
    }
    /**
     * @param collectBO:收藏商品信息，"userId":memoryBean中获取
     * @return 失败或成功信息
     * @auther zhong
     * @description wx/collect/addordelete 添加或取消收藏
     */
    @PostMapping("addordelete")
    public BaseRespVo addordelete(@RequestBody CollectAddOrDelBO collectBO, @RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.ok(null, "登录信息失效", Constant.NOT_FOUND_CODE);
        }
        int code = wxCollectService.updateCollectOp(collectBO,userId);
        if (code == Constant.NOT_FOUND_CODE) {
            return BaseRespVo.invalidParameter("商品不存在");
        } else if (code == Constant.OK_CODE) {
            return BaseRespVo.ok("取消成功");
        } else {
            return BaseRespVo.ok("收藏成功");
        }
    }

}
